<script setup lang="ts">
import { computed, reactive, ref } from "vue";

type Course = {
  c_id: number;
  c_semester: number;
  c_name: String;
  c_selected: boolean;
  c_point: number;
};

const courseList: Array<Course> = reactive([
  {
    c_id: 0,
    c_semester: 12,
    c_name: "高数",
    c_selected: false,
    c_point: 3,
  },
  {
    c_id: 1,
    c_semester: 11,
    c_name: "现代",
    c_selected: false,
    c_point: 2,
  },
  {
    c_id: 3,
    c_semester: 21,
    c_name: "Java程序设计",
    c_selected: false,
    c_point: 2,
  },
  {
    c_id: 2,
    c_semester: 11,
    c_name: "概率论",
    c_selected: false,
    c_point: 2.5,
  },
  {
    c_id: 4,
    c_semester: 32,
    c_name: "web系统框架",
    c_selected: false,
    c_point: 2.5,
  },
]);

function select(item: Course) {
  item.c_selected = !item.c_selected;
}

const showList = courseList.sort((a, b) => a.c_semester - b.c_semester);
const currentSemester = 32;

//使用计算属性计算总学分
const totalPoint = computed(() => {
  const list = courseList
    .filter((i) => i.c_selected)
    .sort((a, b) => a.c_semester - b.c_semester);
  return list.reduce((sum, cur, index) => {
    return sum + cur.c_point;
  }, 0);
});
</script>

<template>
  <div class="select">
    <div class="course-list">
      <p>课程列表</p>
      <span>当前学期：{{ currentSemester }}</span>
      <div v-for="item in showList" :key="item.c_id" class="item-course">
        <input
          type="checkbox"
          :id="item.c_id"
          value="item"
          @click="select(item)"
        />
        <label :for="item.c_id"
          >{{ item.c_name }} - {{ item.c_point }}分 - 学期：{{
            item.c_semester
          }}</label
        >
      </div>
    </div>
    <div class="result">
      <p>选课结果</p>
      <div>
        已选课程：<span
          v-for="item in courseList"
          :key="item.c_id"
          class="item-course"
          ><span v-if="item.c_selected"
            >{{ item.c_name }} - {{ item.c_point }}分</span
          ></span
        >
      </div>
      <div>
        <p>
          学分：<span :style="{ color: totalPoint < 10 ? 'red' : 'green' }">{{
            totalPoint
          }}</span
          >/17.5 (累加学分大于10分为合格)
        </p>
      </div>
    </div>
  </div>
</template>

<style scoped>
.select {
  display: flex;
  width: 100%;
  background-color: #f7f7f7;
}
.course-list {
  flex: 1;
  padding: 20px;
}
.item-course {
  padding: 10px;
}

.result {
  width: 50%;
  padding: 20px;
  background-color: #f7f7f7;
  border-left: 2px solid #ccc;
}
</style>
